﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DNNspot.LiveChat.DataModel;
using DotNetNuke.Common;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;

namespace DNNspot.LiveChat
{
    public partial class AgentChat : ChatPageBase
    {
        // ### EVENTS ######################################################

        protected void Page_PreRender(object sender, EventArgs e)
        {
            IncludeJS();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                LoadControls();

            if (!Agent.IsAgent(UserId))
            {
                Response.Redirect(string.Format(@"/DesktopModules/{0}/ClientChat.aspx", ModuleSettings.FolderName));
            }
        }

        // ### PRIVATE FUNCTIONS ###########################################

        private void IncludeJS()
        {
            if (string.IsNullOrEmpty(HostSettings.GetHostSetting(ModuleSettings.NoJQuery)) && HttpContext.Current.Items["jquery_registered"] == null)
            {
                RegisterJavascript(String.Format("{0}{1}js/jquery-1.3.2.min.js", Globals.ApplicationPath, ChatPageWebPath));
                HttpContext.Current.Items.Add("jquery_registered", "true");
            }

            RegisterJavascript(string.Format("{0}{1}js/dnnspot.livechat.agent.include.js", Globals.ApplicationPath, ChatPageWebPath));

            RegisterJavascript(string.Format("{0}{1}js/jquery.layout.js", Globals.ApplicationPath, ChatPageWebPath));
            RegisterJavascript(string.Format("{0}{1}js/jquery.validationEngine.js", Globals.ApplicationPath, ChatPageWebPath));
            RegisterJavascript(string.Format("{0}{1}js/jquery.validationEngine-en.js", Globals.ApplicationPath, ChatPageWebPath));


            RegisterJavascript(string.Format("{0}{1}js/dnnspot.livechat.agent.js", Globals.ApplicationPath, ChatPageWebPath));
        }

        private void LoadControls()
        {
            var agent = Agent.LoadByUserId(UserController.GetCurrentUserInfo().UserID);

            hidAgentId.Value = agent.AgentId.ToString();
            hidChatPageWebPath.Value = ChatPageWebPath;
            hidIp.Value = Request.UserHostAddress;
            hidPortalId.Value = PortalId.ToString();
            hidUserId.Value = UserId.ToString();
        }
    }
}
